package bastanteo.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import bastanteo.excepcion.DAOExcepcion;
import bastanteo.modelo.Persona;
import bastanteo.util.ConexionBD;

public class PersonaDAO extends BaseDAO{
	
	public void insertar(Persona persona) throws DAOExcepcion {
		//System.out.println("PersonaDAO: insertar(Persona persona)");
		String query = "INSERT INTO persona(codPers, nombre, apeMat, apePat, tipDoc, numDoc) " +
						"VALUES (?,?,?,?,?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, persona.getCodPers());
			stmt.setString(2, persona.getNombre());
			stmt.setString(3, persona.getApeMat());
			stmt.setString(4, persona.getApePat());
			stmt.setString(5, persona.getTipDoc());
			stmt.setString(6, persona.getNumDoc());
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar la persona");
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
	}
	
	public Persona obtener(String codPer) throws DAOExcepcion {
		System.out.println("PersonaDAO: obtener(String codPers)");
		Persona per = new Persona();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String query = "SELECT codPers, nombre,apeMat, apePat, tipDoc, numDoc from poder where codPers=?";
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, codPer);
			rs = stmt.executeQuery();
			if (rs.next()) {
				per.setCodPers(rs.getString("codPers"));
				per.setNombre(rs.getString("nombre"));
				per.setApeMat(rs.getString("apeMat"));		
				per.setApePat(rs.getString("apePat"));
				per.setTipDoc(rs.getString("tipDoc"));
				per.setNumDoc(rs.getString("numDoc"));
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return per;
	}
}
